<?
function formatDate($date){
	$date = date('d/m/Y',strtotime($date));
	return $date;
}
function getBeginningBalance($debtur_code=false){
	$data = getTotal($debtur_code,false,true);
	return (object) $data;
}
function getFilter($debtur_code,$alias=''){
	//$where = " AND ".filterSkada($alias);
	$where = " ";
	if (GetParam("office",""))   $where .= " AND ".$alias."ktrasl = '".GetParam("office","")."' ";
	if (GetParam("curr",""))   $where .= " AND ".$alias."curr = '".GetParam("curr","")."' ";
	if ($debtur_code) $where .=" AND ".$alias."debtur  = '".$debtur_code."' ";
	return $where;
}

function getTotal($debtur,$all=false,$lastMonth=false){
	global $DBConnection;
	$searchMonth = GetParam('searchMonth','');
	$searchYear = GetParam('searchYear','');
	
	if($lastMonth){
		$searchMonth--;
		if(!$searchMonth){
			$searchMonth = 12;
			$searchYear--;
		}
	}	
	$src = $searchYear.'-'.sprintf('%02d',$searchMonth).'-01';
	$curr = GetParam("curr","");
	
	$SQL = "SELECT LAST_DAY('$src') LAST_DATE,TRIM(CUCODE) debtur,CUNAME debnam,
			 IFNULL(SUM(IF('$curr'='IDR',rupiah,jumlah)),0)+ IF('$curr'='IDR',BALANCE_IDR,BALANCE_USD) total_org, 			 
			 IFNULL(SUM(rupiah),0)+IF('$curr'='IDR',BALANCE_IDR,BALANCE_USD_RUPIAH) total_rph 
			FROM tbldebtur a LEFT JOIN `view_soa_receivable` b ON b.debtur = a.CUCODE AND tglbkt<=LAST_DAY('$src') ";
	if (GetParam("office",""))   $SQL .= " AND ktrasl = '".GetParam("office","")."' ";
	if ($curr) $SQL .= " AND curr = '".$curr."' ";
	if ($debtur) $SQL .=" WHERE CUCODE = '".$debtur."' ";
	else $SQL .= " WHERE CUCODE IN(SELECT DISTINCT debtur FROM view_soa_receivable WHERE tglbkt<=LAST_DAY('$src'))";
	$SQL .= " GROUP BY CUCODE ";
	//if($all) $SQL .= " LIMIT 5 ";		
	//die($SQL);
	
	return $all ? $DBConnection->dbc->get_results($SQL,ARRAY_A) : $DBConnection->dbc->get_row($SQL,ARRAY_A);
}

function GridList($debtur_code){
	global $DBConnection;
	$searchMonth = GetParam('searchMonth','');
	$searchYear = GetParam('searchYear','');
	$SQL = "SELECT * FROM `view_soa_receivable` WHERE 
			MONTH(tglbkt) = '$searchMonth' AND YEAR(tglbkt) = '$searchYear' ".getFilter($debtur_code)." ORDER BY tglbkt";
	//die($SQL);
	return $DBConnection->dbc->get_results($SQL,ARRAY_A);
}
?>
